﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Proggy.Web.Cms.ContentModel;
using Proggy.Data.Abstract;
using Newtonsoft.Json;
using Proggy.Data.Entities;
using Proggy.Web.Cms.Cache;
using Proggy.Data;
using Proggy.Web.Cms.Repositories.Membership;
using System.Web.Mvc;
using Proggy.Web.Cms.Context;

namespace Proggy.Web.Cms.Repositories.ContentModel
{
    /// <summary>
    /// Content model data
    /// </summary>
    public class ContentModelDataRepository : IContentModelDataRepository
    {
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="nodeRepo"></param>
        public ContentModelDataRepository(INodeRepository nodeRepo, IContentModelConverter converter)
        {
            this._nodeRepo = nodeRepo;
            this._converter = converter;
        }

        /// <summary>
        /// Returns content model for node id
        /// </summary>
        /// <returns></returns>
        public IContentModel GetContentModelFromNodeId(int nodeId, bool onlyPublished)
        {
            // get node
            PublishableNode node = null;
            if (onlyPublished)
            {
                node = this._nodeRepo.GetPublishableNodes(true).SingleOrDefault(x=>x.PublishableNodeId==nodeId);// PublishableNodes.AsEnumerable().SingleOrDefault(x => x.IsPublished && x.PublishableNodeId == nodeId);
            }
            else
            {
                node = this._nodeRepo.GetPublishableNodeFromNodeId(nodeId);
            }

            return this.ContentModelConverter.ToPublishedAbstractSingle(node);

        }
        
        /// <summary>
        /// Get draft content model (if none exists, will create!!!!)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IContentModel GetDraftContentModelFromId(int id)
        {
            // get publishable
            var publishable = this._nodeRepo.GetPublishableNodes(false).SingleOrDefault(x => x.PublishableNodeId == id);            

            //
            return this.ContentModelConverter.ToDraftAbstractSingle(publishable);
        }       

        //private
        private INodeRepository _nodeRepo;
        private IContentModelConverter _converter;

        public IContentModelConverter ContentModelConverter
        {
            get { return this._converter; }
        }
    }
}
